import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:orginone/components/XStatefulWidget/XStatefulWidget.dart';
import 'package:orginone/components/ChatSessionWidget/components/ChatBoxWidget/ChatBoxWidget.dart';
import 'package:orginone/components/ChatSessionWidget/components/MessageListWidget/components/DetailItemWidget/DetailItemWidget.dart';
import 'package:orginone/components/ChatSessionWidget/components/MessageListWidget/MessageListWidget.dart';
import 'package:orginone/components/EmptyWidget/EmptyChat.dart';
import 'package:orginone/dart/core/chat/session.dart';
import 'package:orginone/dart/core/target/base/target.dart';

class ChatSessionWidget extends XStatefulWidget {
  ChatSessionWidget({super.key, super.data});
  @override
  State<StatefulWidget> createState() => _ChatSessionWidgetState();
}

class _ChatSessionWidgetState
    extends XStatefulState<ChatSessionWidget, dynamic> {
  late ChatBoxController chatBoxCtrl;
  late String emitterKey;
  // late dynamic _data;

  @override
  void initState() {
    super.initState();
    // if (!Get.isRegistered<MessageChatController>()) {
    //   chatCtrl = MessageChatController();
    //   chatCtrl.context = context;
    //   Get.put(chatCtrl);
    // } else {
    //   chatCtrl = Get.find<MessageChatController>();
    //   chatCtrl.context = context;
    // }
    if (!Get.isRegistered<PlayController>()) {
      PlayController playCtrl = PlayController();
      Get.lazyPut(() => playCtrl);
    }
    if (!Get.isRegistered<ChatBoxController>()) {
      chatBoxCtrl = ChatBoxController();
      Get.put(chatBoxCtrl);
    } else {
      chatBoxCtrl = Get.find<ChatBoxController>();
    }
    // emitterKey = relationCtrl.subscribe((key, args) {
    //   if (null != data && null != relationCtrl.user) {
    //     // ToastUtils.showMsg(msg: "${data.id}");
    //     data = relationCtrl.findMemberChat(data.id, data.belongId);
    //     if (mounted && null != data) {
    //       // ToastUtils.showMsg(msg: "刷新对象：${data?.id}");
    //       // data.clearCache();
    //       setState(() {});
    //     }
    //   }
    // }, false);
  }

  @override
  Widget buildWidget(BuildContext context, dynamic data) {
    // state.noReadCount = state.chat.noReadCount;
    ISession? session;
    if (data is ISession) {
      session = data;
    } else if (data is ITarget) {
      session = data.session;
    }

    return null != session
        ? GestureDetector(
            onTap: () {
              FocusScope.of(context).requestFocus(FocusNode());
              chatBoxCtrl.eventFire(context, InputEvent.clickBlank, session!);
            },
            child: Column(
              children: [
                Expanded(child: MessageListWidget(chat: session)),
                ChatBoxWidget(chat: session, controller: chatBoxCtrl)
              ],
            ),
          )
        : const EmptyChat();
  }
}
